/**
 * @description 客服系统,单条会话连接
 * @AUTH along
 * @DATA 2020-10-14
 */
export default class MessageSocket {
    constructor (context, object) {
        this.json = object || {};//参数
        this.context = context;//this
        this.ws = null;//socket对象
        this.socketUrl = '';//socket地址
        this.chat_no = '';
        this.session_no = '';
        if(JSON.stringify(this.json) !== '{}') {
            this.socketUrl = object.socketUrl;
            this.chat_no = object.chat_no;
            this.session_no = object.session_no;
        }
        this.init();//初始化连接
    }

    init () {
        if(!Reflect.has(window, "WebSocket")) {
            this.context.$notify({
                title: '提示',
                message: '您的浏览器不支持WebSocket',
                type: 'warning',
                duration: 2000
            });
            return false;
        }
        if(!this.socketUrl) {
            this.context.$notify({
                title: '提示',
                message: 'WebSocket地址为空',
                type: 'warning',
                duration: 2000
            });
            return false;
        }

        this.ws = new WebSocket(this.socketUrl);

        this.ws.addEventListener('open', () => {
            // console.log('----连接状态已发送----');
            this.ws.send(JSON.stringify({
                cmd: 'kf_server_chat',
                data: {
                    chat_no: this.chat_no,
                    session_no: this.session_no
                }
            }));
        });

        this.ws.addEventListener('close', resp => {
            this.ws.close();
            // console.log('----监听会话关闭了----', resp.currentTarget.readyState);
        });
    }
}